# views.py
import os
import datetime
from django import forms
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
from django.shortcuts import render
from django.conf import settings
from urllib.parse import urljoin
from django.views.decorators.csrf import csrf_exempt

from app01 import models
from app01.utils.layUI import LayUiForm, LayUiModelForm


@csrf_exempt
def quick_upload(request):
    """文件上传-单个"""
    if request.method == 'GET':
        return render(request, 'upload/quick-file.html')

    if request.method == 'POST':
        file_obj = request.FILES.get('files')
        print(file_obj.name)  # 文件名 xxx.png
        # 获取当前日期和时间
        now = datetime.datetime.now()
        date_str = now.strftime('%Y-%m-%d')
        timestamp_str = now.strftime('%Y%m%d%H%M%S')

        # 创建日期文件夹
        date_folder = os.path.join(settings.MEDIA_ROOT, date_str)
        os.makedirs(date_folder, exist_ok=True)

        # 使用FileSystemStorage来存储文件
        fs = FileSystemStorage(location=date_folder)

        # 安全处理文件名并加上时间戳
        file_name = os.path.basename(file_obj.name)
        timestamped_file_name = f"{timestamp_str}_{file_name}"
        filename = fs.save(timestamped_file_name, file_obj)  # 保存文件
        file_url = os.path.join(settings.MEDIA_URL, date_str, filename).replace('\\', '/')
        # 获取当前项目的基地址
        base_url = request.build_absolute_uri('/')
        # 生成完整的文件访问地址
        full_url = urljoin(base_url, file_url)
        # 返回上传成功的文件访问地址
        response_content = f'文件上传成功，访问地址: {full_url}'
        return HttpResponse(response_content)

    return HttpResponse('仅支持GET和POST请求')


@csrf_exempt
def multi_file_upload(request):
    """文件上传-多个"""
    if request.method == 'GET':
        return render(request, 'upload/multi-file.html')
    if request.method == 'POST':
        # 获取上传的文件列表
        files = request.FILES.getlist('files')
        if not files:
            return HttpResponse('没有文件上传')

        # 获取当前日期和时间
        now = datetime.datetime.now()
        date_str = now.strftime('%Y-%m-%d')
        timestamp_str = now.strftime('%Y%m%d%H%M%S')

        # 创建日期文件夹
        date_folder = os.path.join(settings.MEDIA_ROOT, date_str)
        os.makedirs(date_folder, exist_ok=True)

        # 使用FileSystemStorage来存储文件
        fs = FileSystemStorage(location=date_folder)

        # 存储每个文件并记录文件的访问 URL
        uploaded_files_urls = []
        for file_obj in files:
            # 安全处理文件名并加上时间戳
            file_name = os.path.basename(file_obj.name)
            timestamped_file_name = f"{timestamp_str}_{file_name}"
            filename = fs.save(timestamped_file_name, file_obj)
            # 生成文件的访问 URL
            file_url = os.path.join(settings.MEDIA_URL, date_str, filename).replace('\\', '/')
            # 获取当前项目的基地址
            base_url = request.build_absolute_uri('/')
            # 生成完整的文件访问地址
            full_url = urljoin(base_url, file_url)
            uploaded_files_urls.append(full_url)

        # 返回上传成功的文件列表
        response_content = '<br>'.join([f'文件上传成功，访问地址: {url}' for url in uploaded_files_urls])
        return HttpResponse(response_content)

    return HttpResponse('仅支持GET和POST请求')


class UpLoadForm(LayUiForm):
    layui_exclude_fields = ['avatar']
    name = forms.CharField(label='姓名')
    age = forms.IntegerField(label='年龄')
    avatar = forms.FileField(label='头像', required=False)


def upload_form(request):
    """
        文件上传，基于Form上传
    """
    title = "Form上传"
    if request.method == 'GET':
        form = UpLoadForm()
        return render(request, 'upload/form.html', {"form": form, "title": title})
    form = UpLoadForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        print(
            form.cleaned_data)  # 读取到的内容，自己开始处理 {'name': '路人甲', 'age': 1024, 'avatar': <InMemoryUploadedFile: logo.png (image/png)>}
        # 1、读取图片内容,写入到文件夹中，并返回文件路径并存储文件路径到库中 S
        file_obj = form.cleaned_data.get("avatar")
        # 获取当前日期和时间
        now = datetime.datetime.now()
        date_str = now.strftime('%Y-%m-%d')
        timestamp_str = now.strftime('%Y%m%d%H%M%S')

        # 创建日期文件夹
        date_folder = os.path.join(settings.MEDIA_ROOT, date_str)
        os.makedirs(date_folder, exist_ok=True)

        # 使用FileSystemStorage来存储文件
        fs = FileSystemStorage(location=date_folder)

        # 安全处理文件名并加上时间戳
        file_name = os.path.basename(file_obj.name)
        timestamped_file_name = f"{timestamp_str}_{file_name}"
        filename = fs.save(timestamped_file_name, file_obj)  # 保存文件
        file_url = os.path.join(settings.MEDIA_URL, date_str, filename).replace('\\', '/')
        # 1、读取图片内容,写入到文件夹中，并返回文件路径并存储文件路径到库中 E
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            avatar=file_url
        )
        return HttpResponse('新建成功')

    return render(request, 'upload/form.html', {"form": form, "title": title})


class UpLoadModelForm(LayUiModelForm):
    layui_exclude_fields = ['logo']
    class Meta:
        model = models.City
        fields = '__all__'


def upload_model_form(request):
    """
        文件上传，基于ModelForm上传
    """
    title = "ModelForm上传"
    if request.method == 'GET':
        form = UpLoadModelForm()
        return render(request, 'upload/model_form.html', {"form": form, "title": title})

    form = UpLoadModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        form.save()
        return HttpResponse('新建成功')
    return render(request, 'upload/model_form.html', {"form": form, "title": title})